package springfixture;

import java.util.HashMap;
import java.util.Map;

import org.springframework.util.Assert;

import springfixture.results.Result;
import fit.Parse;

/*
 * Copyright 2002-2005 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * This is an Adapter that exports a Spring Bean to Fit / FitNesse
 */
public class SpringColumnFixture extends SpringTableFixture {

    public void doRows(Parse rows) {
        createSpringBean(rows.parts);
        createHeaders(rows.more.parts);
        super.doRows(rows.more.more);
    }

    void createHeaders(Parse parts) {
        header = new String[parts.size()];
        int i = 0;
        while (parts != null) {
            header[i] = parts.text();
            parts = parts.more;
            i++;
        }
    }

    protected void doStaticTable(int rows) {
        for (int row = 0; row < rows; row++) {
            Map<String, String> properties = new HashMap<String, String>();
            for (int column = 0; column < header.length; column++) {
                if (isMethodCallOrPropertyRead(header[column])) {
                    Result result = springFitAdapter
                            .handleSingleResultMethodCallOrPropertyRead(
                                    getMethodOrPropertyName(header[column]),
                                    properties);
                    properties = new HashMap<String, String>();
                    result.render(getCell(row, column));
                } else {
                    properties.put(header[column], getText(row, column));
                }
            }
        }

    }

    public static String getMethodOrPropertyName(String header) {
        Assert.isTrue(isMethodCallOrPropertyRead(header));
        return header.substring(0, header.length() - 1);
    }

    public static boolean isMethodCallOrPropertyRead(String header) {
        return header.endsWith("?");
    }

}
